package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.*;
import com.sc.nft.entity.ImGroup;
import com.sc.nft.entity.ImGroupRule;
import com.sc.nft.entity.StaticData;
import com.sc.nft.entity.UserInfo;
import com.sc.nft.entity.dto.*;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.ImCreateGroupTypeEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.helper.ImAccountHelper;
import com.sc.nft.pool.SysMemberPool;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.ImGroupRuleService;
import com.sc.nft.service.ImGroupService;
import com.sc.nft.sup.PageRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
@RefreshScope
public class ImGroupServiceImpl implements ImGroupService {

    private final ImGroupDao imGroupDao;

    private final ImAccountHelper imAccountHelper;

    private final UserInfoDao userInfoDao;

    private final UserCreatorInfoDao userCreatorInfoDao;

    private final ImGroupRuleService imGroupRuleService;

    private final StaticDataDao staticDataDao;

    private final UserCollectionDao collectionDao;

    private final RedisTemplate redisTemplate;

    @Value("${user.add.group.url}")
    private String groupNameUrl;

    @Value("${dimensional.code.url}")
    private String dimensionalCodeUrl;

    @Override
    public Boolean groupIsExist(Long id) {
        return imGroupDao.groupIsExist(id);
    }

    @Override
    public ImGroupInfoVO getByDaoIdGroup(Long id) {
        // 获取指定dao的群组
        List<ImGroup> info = imGroupDao.getByDaoIdGroup(id);
        if (CollUtil.isEmpty(info)) {
            return null;
        }
        List<String> collect = info.stream().map(ImGroup::getGroupId).collect(Collectors.toList());
        ImGetGroupInfoDTO imGetGroupInfoDTO = new ImGetGroupInfoDTO();
        imGetGroupInfoDTO.setGroupIdList(collect);
        // 获取腾讯上注册的所有群组
        ImGroupInfoVO groupInfo = (ImGroupInfoVO) imAccountHelper.getGroupInfo(imGetGroupInfoDTO, ImGroupInfoVO.class);
        groupInfo.setGroupInfo(groupInfo.getGroupInfo().stream().filter(groupInfoDTO -> groupInfoDTO.getErrorCode().equals(0)).collect(Collectors.toList()));
        // 获取用户当前所有的群组
        ImGetJoinedGroupListDTO imGetJoinedGroupListDTO = new ImGetJoinedGroupListDTO();
        imGetJoinedGroupListDTO.setGroupType("Public");
        imGetJoinedGroupListDTO.setMemberAccount(Convert.toStr(UserPool.getUser().getId()));
        ImGetJoinedGroupListVO imGetJoinedGroupListVO = (ImGetJoinedGroupListVO) imAccountHelper.getJoinedGroupList(imGetJoinedGroupListDTO, ImGetJoinedGroupListVO.class);

        // 循环组合处理群组数据
        if (CollUtil.isEmpty(groupInfo.getGroupInfo())) {
            return groupInfo;
        }
        groupInfo.getGroupInfo().forEach(groupInfoDTO -> {
            // 把排序写入到字段中
            groupInfoDTO.setSort(info.stream().filter(imGroup -> imGroup.getGroupId().equals(groupInfoDTO.getGroupId())).collect(Collectors.toList()).get(0).getSort());
            // 判定用户是否有加入的群组
            List<ImGetJoinedGroupListVO.GroupIdListDTO> groupIdList = imGetJoinedGroupListVO.getGroupIdList();
            if (CollUtil.isEmpty(groupIdList)) {
                groupInfoDTO.setIsExist(Boolean.FALSE);
                return;
            }
            // 判定当前用户是否加入该群组
            List<ImGetJoinedGroupListVO.GroupIdListDTO> collect1 = imGetJoinedGroupListVO.getGroupIdList().stream().filter(data -> data.getGroupId().equals(groupInfoDTO.getGroupId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect1)) {
                groupInfoDTO.setIsExist(Boolean.TRUE);
            } else {
                groupInfoDTO.setIsExist(Boolean.FALSE);
            }
        });
        // 数据排序后返回给前段
        groupInfo.setGroupInfo(groupInfo.getGroupInfo().stream().sorted(Comparator.comparing(ImGroupInfoVO.GroupInfoDTO::getSort).reversed()).collect(Collectors.toList()));
        return groupInfo;
    }

    @Override
    public void userAddGroup(String id, UserInfo user) {
        if (BeanUtil.isEmpty(user)) {
            throw new GlobalRunTimeException("用户数据异常");
        }
        if (!user.getIsSm()) {
            throw new GlobalRunTimeException("未实名");
        }
        ImGroup imGroup = imGroupDao.getByGroupId(id);
        if (BeanUtil.isEmpty(imGroup)) {
            throw new GlobalRunTimeException("群组不存在或已解散");
        }
        // 先注册,否则无法加群
        imAccountHelper.accountImport(Convert.toStr(user.getId()), user.getNickName(), user.getAvatarImg(), JSONObject.class);
        ImAddGroupMemberDTO imAddGroupMemberDTO = new ImAddGroupMemberDTO();
        imAddGroupMemberDTO.setMemberAccount(Arrays.asList(Convert.toStr(user.getId())));
        imAddGroupMemberDTO.setGroupId(imGroup.getGroupId());
        imAddGroupMemberDTO.setSilence(0);
        // 用户加入群组.
        JSONObject addGroupMember = (JSONObject) imAccountHelper.addGroupMember(imAddGroupMemberDTO, JSONObject.class);
        if (Convert.toInt(addGroupMember.get("ErrorCode")).equals(10014)) {
            throw new GlobalRunTimeException("群已满员");
        }
        if (!Convert.toInt(addGroupMember.get("ErrorCode")).equals(0)) {
            throw new GlobalRunTimeException("入群异常");
        }
        List<JSONObject> memberList = (List<JSONObject>) addGroupMember.get("MemberList");
        JSONObject jsonObject = memberList.get(0);
        Integer result = Convert.toInt(jsonObject.get("Result"));
        if (!result.equals(1)) {
            throw new GlobalRunTimeException("已经是群成员");
        }
    }

    @Override
    public void adminCreateGroup(ImCreateGroupDTO imCreateGroupDTO) {
//        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(imCreateGroupDTO.getDaoId());
//        if (BeanUtil.isEmpty(userCreatorInfo)) {
//            throw new GlobalRunTimeException("该Dao不存在");
//        }

        // 创建成功后,把群转移给群主
        UserInfo oneByUserTel = userInfoDao.getOneByUserTel(imCreateGroupDTO.getUserTel());
        if (BeanUtil.isEmpty(oneByUserTel)) {
            throw new GlobalRunTimeException("用户不存在");
        }
        // 不确定群主是否已经注册,把用户注册掉
        imAccountHelper.accountImport(Convert.toStr(oneByUserTel.getId()), oneByUserTel.getNickName(), oneByUserTel.getAvatarImg(), JSONObject.class);

        // 指定群主
        imCreateGroupDTO.setOwnerAccount(Convert.toStr(oneByUserTel.getId()));
        // 创建群组
        JSONObject group = (JSONObject) imAccountHelper.createGroup(imCreateGroupDTO, JSONObject.class);
        // 组id
        String groupId = (String) group.get("GroupId");
        if (StrUtil.isEmpty(groupId)) {
            throw new GlobalRunTimeException("创建失败,联系技术人员.");
        }
        // 数据落库
        ImGroup imGroup = new ImGroup();
        imGroup.setGroupId(groupId);
        imGroup.setUserId(oneByUserTel.getId());
        imGroup.setSort(imCreateGroupDTO.getSort());
        imGroup.setDaoId(imCreateGroupDTO.getDaoId());
        imGroup.setGroupMasterId(oneByUserTel.getId());
        imGroup.setCreateTime(DateUtil.date());
        imGroup.setModifyTime(DateUtil.date());
        if (BeanUtil.isEmpty(SysMemberPool.getMember())) {
            imGroup.setCreateId(0L);
            imGroup.setModifyId(0L);
        } else {
            imGroup.setCreateId(SysMemberPool.getMember().getId());
            imGroup.setModifyId(SysMemberPool.getMember().getId());
        }

        imGroup.setStatus(imCreateGroupDTO.getStatus());
        imGroup.setOfficial(imCreateGroupDTO.getOfficial());
        imGroup.insert();
        ImSendGroupMsgDTO imSendGroupSystemNotificationDTO = new ImSendGroupMsgDTO();
        Map map = new HashMap();
        Map text = new HashMap();
        List<Map> list = new ArrayList<>();
        text.put("Text", "群创建成功");
        map.put("MsgType", "TIMTextElem");
        map.put("MsgContent", text);
        list.add(map);
        imSendGroupSystemNotificationDTO.setFromAccount(Convert.toStr(oneByUserTel.getId()));
        imSendGroupSystemNotificationDTO.setGroupId(groupId);
        imSendGroupSystemNotificationDTO.setMap(list);
        imAccountHelper.sendGroupMsg(imSendGroupSystemNotificationDTO, JSONObject.class);
    }

    @Override
    public void adminDestroyGroup(String groupId) {
        ImGroup byGroupId = imGroupDao.getByGroupId(groupId);
        if (!BeanUtil.isEmpty(byGroupId)) {
            if (byGroupId.getOfficial().equals(1)) {
                throw new GlobalRunTimeException("官方群无法解散");
            }
        }
        int i = imGroupDao.deleteGroupId(groupId);
        if (i==0) {
            throw new GlobalRunTimeException("解散失败");
        }
        JSONObject jsonObject = (JSONObject) imAccountHelper.destroyGroup(groupId, JSONObject.class);
        if (!Convert.toInt(jsonObject.get("ErrorCode")).equals(0)) {
            throw new GlobalRunTimeException("群组解散失败");
        }
    }

    @Override
    public Page<AdminGroupListVO> adminGroupList(PageRequest pageRequest) {
        Page<AdminGroupListVO> adminGroupListVOPage = imGroupDao.adminGroupList(pageRequest);
        if (CollUtil.isEmpty(adminGroupListVOPage.getRecords())) {
            return adminGroupListVOPage;
        }
        List<AdminGroupListVO> records = adminGroupListVOPage.getRecords();
        records.forEach(adminGroupListVO -> {
            ImGetGroupInfoDTO imGetGroupInfoDTO = new ImGetGroupInfoDTO();
            imGetGroupInfoDTO.setGroupIdList(Arrays.asList(adminGroupListVO.getGroupId()));
            ImGroupInfoAllResultVO imGroupInfoVO = (ImGroupInfoAllResultVO) imAccountHelper.getGroupInfo(imGetGroupInfoDTO, ImGroupInfoAllResultVO.class);
            ImGroupInfoAllResultVO.GroupInfoDTO groupInfoDTO = imGroupInfoVO.getGroupInfo().get(0);
            adminGroupListVO.setGroupName(groupInfoDTO.getName());
            adminGroupListVO.setMaxMemberNum(groupInfoDTO.getMaxMemberNum());
            adminGroupListVO.setFaceUrl(groupInfoDTO.getFaceUrl());
            adminGroupListVO.setMemberNum(groupInfoDTO.getMemberNum());
            List<Map> appMemberDefinedData = groupInfoDTO.getAppDefinedData();
            if (CollUtil.isEmpty(appMemberDefinedData)) {
                adminGroupListVO.setOperation(Boolean.FALSE);
            } else {
                appMemberDefinedData.forEach(map -> {
                    String key = (String) map.get("Key");
                    if (key.equals("lockdown")) {
                        adminGroupListVO.setOperation(Convert.toBool(map.get("Value")));
                    } else {
                        adminGroupListVO.setOperation(Boolean.FALSE);
                    }

                });
            }
        });

        return adminGroupListVOPage;
    }

    @Override
    public void modifierGroup(AdminModifierGroupDTO adminModifierGroupDTO) {
        ImGroup byGroupId = imGroupDao.getByGroupId(adminModifierGroupDTO.getGroupId());
        if (BeanUtil.isEmpty(byGroupId)) {
            throw new GlobalRunTimeException("组不存在");
        }
        if (adminModifierGroupDTO.getSort() != null) {
            ImGroup imGroup = new ImGroup();
            imGroup.setSort(adminModifierGroupDTO.getSort());
            imGroupDao.modifierGroup(adminModifierGroupDTO.getGroupId(), imGroup);
        }
        ImModifyGroupBaseInfoDTO imModifyGroupBaseInfoDTO = new ImModifyGroupBaseInfoDTO();
        imModifyGroupBaseInfoDTO.setGroupId(adminModifierGroupDTO.getGroupId());
        imModifyGroupBaseInfoDTO.setName(adminModifierGroupDTO.getGroupName());
        imModifyGroupBaseInfoDTO.setFaceUrl(adminModifierGroupDTO.getFaceUrl());
        imAccountHelper.modifyGroupBaseInfo(imModifyGroupBaseInfoDTO, JSONObject.class);

    }

    @Override
    public void searchUserInfoAddGroup(SearchUserInfoAddGroupDTO searchUserInfoAddGroupDTO) {
        UserInfo oneByUserTel = userInfoDao.getOneByUserTel(searchUserInfoAddGroupDTO.getUserTel());
        if (BeanUtil.isEmpty(oneByUserTel)) {
            throw new GlobalRunTimeException("用户不存在");
        }
        ImGetGroupInfoDTO imGetGroupInfoDTO = new ImGetGroupInfoDTO();
        imGetGroupInfoDTO.setGroupIdList(Arrays.asList(searchUserInfoAddGroupDTO.getGroupId()));

        ImGroupInfoVO imGroupInfoVO = (ImGroupInfoVO) imAccountHelper.getGroupInfo(imGetGroupInfoDTO, ImGroupInfoVO.class);
        if (BeanUtil.isEmpty(imGroupInfoVO.getGroupInfo())) {
            throw new GlobalRunTimeException("群不存在");
        }
        List<ImGroupInfoVO.GroupInfoDTO> collect = imGroupInfoVO.getGroupInfo().stream().filter(groupInfoDTO -> groupInfoDTO.getErrorCode().equals(0)).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            throw new GlobalRunTimeException("群不存在");
        }
        ImGroupInfoVO.GroupInfoDTO groupInfoDTO = collect.get(0);
        if (groupInfoDTO.getMemberNum() >= groupInfoDTO.getMaxMemberNum()) {
            throw new GlobalRunTimeException("群成员已满");
        }
        userAddGroup(searchUserInfoAddGroupDTO.getGroupId(), oneByUserTel);
    }

    @Override
    public void transferGroupMaster(TransferGroupMasterDTO transferGroupMasterDTO) {
        imGroupDao.transferGroupMaster(transferGroupMasterDTO);
    }

    /**
     * 所有用户加入群组
     */
    @Override
    public Boolean allUserAddGroup() {
        AvailableGroupDTO availableGroup = getAvailableGroup();
        Page page = new Page();
        page.setCurrent(1L);
        page.setSize(availableGroup.getGroupCapacity());
        List<Long> collect = imGroupRuleService.getAll().stream().map(ImGroupRule::getId).collect(Collectors.toList());
        List<UserInfo> userIsSmAndIsOfficialLimit = userInfoDao.getUserIsSmAndIsOfficialLimit(page, collect);
        if (CollUtil.isEmpty(userIsSmAndIsOfficialLimit)) {
            return Boolean.FALSE;
        }
        userIsSmAndIsOfficialLimit.forEach(userInfo -> {
            Long id = userInfo.getId();
            String nickName = userInfo.getNickName();
            String avatarImg = userInfo.getAvatarImg();
            imAccountHelper.accountImport(Convert.toStr(id), nickName, avatarImg, JSONObject.class);
            ImAddGroupMemberDTO imAddGroupMemberDTO = new ImAddGroupMemberDTO();
            imAddGroupMemberDTO.setMemberAccount(Arrays.asList(Convert.toStr(id)));
            imAddGroupMemberDTO.setGroupId(availableGroup.getImGroup().getGroupId());
            imAddGroupMemberDTO.setSilence(0);
            imAccountHelper.addGroupMember(imAddGroupMemberDTO, JSONObject.class);
            userInfoDao.updateUserByIdGroup(userInfo.getId(),1);
        });
        if (availableGroup.getGroupInfoDTO().getMemberNum() + userIsSmAndIsOfficialLimit.size() >= availableGroup.getGroupInfoDTO().getMaxMemberNum()) {
            availableGroup.getImGroup().setStatus(1);
            availableGroup.getImGroup().updateById();
        }
        return Boolean.TRUE;
    }

    @Override
    public void voluntarilyAllUserAddGroup() {
        while (true) {
            Boolean aBoolean = allUserAddGroup();
            if (!aBoolean) {
                break;
            }
        }
    }


    @Override
    public AvailableGroupDTO getAvailableGroup() {
        AvailableGroupDTO availableGroupDTO = new AvailableGroupDTO();
        // 最新一条的群组
        ImGroup officialLimitFinallyData = imGroupDao.getOfficialLimitFinallyData();
        if (BeanUtil.isEmpty(officialLimitFinallyData)) {
//            没有群组,新建群
            return getAvailableGroupDTO(availableGroupDTO);
        }
        // 群组存在,查询群组是否满员
        ImGetGroupInfoDTO imGetGroupInfoDTO = new ImGetGroupInfoDTO();
        imGetGroupInfoDTO.setGroupIdList(Arrays.asList(officialLimitFinallyData.getGroupId()));
        ImGroupInfoVO groupInfo = (ImGroupInfoVO) imAccountHelper.getGroupInfo(imGetGroupInfoDTO, ImGroupInfoVO.class);
        List<ImGroupInfoVO.GroupInfoDTO> collect = groupInfo.getGroupInfo().stream().filter(groupInfoDTO -> groupInfoDTO.getErrorCode().equals(0)).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
//            没有群组,新建群
            return getAvailableGroupDTO(availableGroupDTO);
        }
        ImGroupInfoVO.GroupInfoDTO groupInfoDTO = collect.get(0);
        if (groupInfoDTO.getMaxMemberNum() > groupInfoDTO.getMemberNum()) {
            availableGroupDTO.setImGroup(officialLimitFinallyData);
            availableGroupDTO.setGroupCapacity(groupInfoDTO.getMaxMemberNum() - groupInfoDTO.getMemberNum());
            availableGroupDTO.setGroupInfoDTO(groupInfoDTO);
            return availableGroupDTO;
        } else {
            officialLimitFinallyData.setStatus(1);
            officialLimitFinallyData.updateById();
            return getAvailableGroupDTO(availableGroupDTO);
        }
    }

    @Override
    public String userCreationGroup(UserCreationGroupDTO userCreationGroupDTO) {
        UserInfo user = UserPool.getUser();

        // 城主才可以创建群组.
        StaticData cityLordCollectionId = staticDataDao.getByType("city_lord_collection_id");
        Long collectionId = Convert.toLong(cityLordCollectionId.getValue());
        Integer countByCollectionId = collectionDao.getCountByCollectionId(collectionId, user.getId());
        if (countByCollectionId <= 0) {
            throw new GlobalRunTimeException("只有城主才能发起群聊");
        }

        // 不确定群主是否已经注册,把用户注册掉(鬼知道定时任务扫没扫到他)
        imAccountHelper.accountImport(Convert.toStr(user.getId()), user.getNickName(), user.getAvatarImg(), JSONObject.class);
        ImCreateGroupDTO imCreateGroupDTO = new ImCreateGroupDTO();
        // 指定群主
        imCreateGroupDTO.setOwnerAccount(Convert.toStr(user.getId()));
        // 群组类型
        imCreateGroupDTO.setType(ImCreateGroupTypeEnum.PUBLIC);
        // 群成员上限
        imCreateGroupDTO.setMaxMemberCount(2000);
        // 群组名称
        imCreateGroupDTO.setName(userCreationGroupDTO.getGroupName());
        // 入群模式
        imCreateGroupDTO.setApplyJoinOption("FreeAccess");
        if (!StrUtil.isEmpty(userCreationGroupDTO.getUrl())) {
            StaticData imgHost = staticDataDao.getByType("imgHost");
            userCreationGroupDTO.setUrl(StrUtil.format("{}{}", imgHost.getValue(), userCreationGroupDTO.getUrl()));
        }
        // 指定对应的头像
        imCreateGroupDTO.setFaceUrl(StrUtil.isEmpty(userCreationGroupDTO.getUrl()) ? groupNameUrl : userCreationGroupDTO.getUrl());
        // 创建群组
        JSONObject group = (JSONObject) imAccountHelper.createGroup(imCreateGroupDTO, JSONObject.class);
        if (!Convert.toInt(group.get("ErrorCode")).equals(0)) {
            throw new GlobalRunTimeException(Convert.toStr(group.get("ErrorInfo")));
        }
        // 组id
        String groupId = (String) group.get("GroupId");
        if (StrUtil.isEmpty(groupId)) {
            throw new GlobalRunTimeException("创建失败,联系技术人员.");
        }
        // 数据落库
        ImGroup imGroup = new ImGroup();
        imGroup.setGroupId(groupId);
        imGroup.setUserId(user.getId());
        imGroup.setSort(imCreateGroupDTO.getSort());
        imGroup.setDaoId(imCreateGroupDTO.getDaoId());
        imGroup.setGroupMasterId(user.getId());
        imGroup.setCreateTime(DateUtil.date());
        imGroup.setModifyTime(DateUtil.date());
        if (BeanUtil.isEmpty(SysMemberPool.getMember())) {
            imGroup.setCreateId(0L);
            imGroup.setModifyId(0L);
        } else {
            imGroup.setCreateId(SysMemberPool.getMember().getId());
            imGroup.setModifyId(SysMemberPool.getMember().getId());
        }

        imGroup.setStatus(0);
        imGroup.setOfficial(0);
        imGroup.insert();
        ImSendGroupMsgDTO imSendGroupSystemNotificationDTO = new ImSendGroupMsgDTO();
        Map map = new HashMap();
        Map text = new HashMap();
        List<Map> list = new ArrayList<>();
        text.put("Text", "群创建成功");
        map.put("MsgType", "TIMTextElem");
        map.put("MsgContent", text);
        list.add(map);
        imSendGroupSystemNotificationDTO.setFromAccount(Convert.toStr(user.getId()));
        imSendGroupSystemNotificationDTO.setGroupId(groupId);
        imSendGroupSystemNotificationDTO.setMap(list);
        imAccountHelper.sendGroupMsg(imSendGroupSystemNotificationDTO, JSONObject.class);
        String format = StrUtil.format("userCreationGroupTime:{}", UserPool.getUser().getId());
        // 倒计时30秒
        redisTemplate.opsForValue().set(format, "1", 30, TimeUnit.SECONDS);
        return groupId;
    }

    @Override
    public GenerateTwoDimensionalCodeVO generateTwoDimensionalCode(String groupId) {
        ImGetGroupInfoDTO imGetGroupInfoDTO = new ImGetGroupInfoDTO();
        imGetGroupInfoDTO.setGroupIdList(Arrays.asList(groupId));
        ImGroupInfoAllResultVO imGroupInfoVO = (ImGroupInfoAllResultVO) imAccountHelper.getGroupInfo(imGetGroupInfoDTO, ImGroupInfoAllResultVO.class);
        List<ImGroupInfoAllResultVO.GroupInfoDTO> collect = imGroupInfoVO.getGroupInfo().stream().filter(groupInfoDTO -> groupInfoDTO.getErrorCode().equals(0)).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            throw new GlobalRunTimeException("群不存在或已解散");
        }
        ImGroupInfoAllResultVO.GroupInfoDTO groupInfoDTO = collect.get(0);
        GenerateTwoDimensionalCodeVO generateTwoDimensionalCodeVO = new GenerateTwoDimensionalCodeVO();
        generateTwoDimensionalCodeVO.setFaceUrl(groupInfoDTO.getFaceUrl());
        generateTwoDimensionalCodeVO.setName(groupInfoDTO.getName());
        generateTwoDimensionalCodeVO.setPeopleSum(groupInfoDTO.getMemberNum());
        generateTwoDimensionalCodeVO.setExpireTime(DateUtil.offsetDay(new Date(), 7));
        generateTwoDimensionalCodeVO.setDimensionalCodeUrl(dimensionalCodeUrl);
        generateTwoDimensionalCodeVO.setPattern(groupInfoDTO.getApplyJoinOption().equals("FreeAccess") ? Boolean.FALSE : Boolean.TRUE);
        String qrCode = UUID.randomUUID().toString();
        generateTwoDimensionalCodeVO.setQrCode(qrCode);
        redisTemplate.opsForValue().set(StrUtil.format("QRCODE:{}-{}", qrCode, groupId), "1", 7, TimeUnit.DAYS);
        return generateTwoDimensionalCodeVO;
    }

    @Override
    public void groupBanned(String groupId, Boolean operation) {
        String muteAllMember = "";
        String lockdown = Boolean.TRUE.toString();
        if (operation) {
            muteAllMember = "On";
        } else {
            muteAllMember = "Off";
            lockdown = Boolean.FALSE.toString();
        }

        ImModifyGroupBaseInfoDTO imModifyGroupBaseInfoDTO = new ImModifyGroupBaseInfoDTO();
        imModifyGroupBaseInfoDTO.setGroupId(groupId);
        imModifyGroupBaseInfoDTO.setMuteAllMember(muteAllMember);
        List<Map> maps = new ArrayList<>();
        Map map = new HashMap();
        map.put("Key", "lockdown");
        map.put("Value", lockdown);
        maps.add(map);
        imModifyGroupBaseInfoDTO.setMap(maps);
        imAccountHelper.modifyGroupBaseInfo(imModifyGroupBaseInfoDTO, JSONObject.class);
    }

    @Override
    public UserIsExistGroupVO userIsExistGroup(String groupId) {
        UserIsExistGroupVO userIsExistGroupVO = new UserIsExistGroupVO();
        ImGetRoleInGroupDTO imGetRoleInGroupDTO = new ImGetRoleInGroupDTO();
        imGetRoleInGroupDTO.setGroupId(groupId);
        imGetRoleInGroupDTO.setUserAccount(Arrays.asList(Convert.toStr(UserPool.getUser().getId())));

        JSONObject jsonObject = (JSONObject) imAccountHelper.getRoleInGroup(imGetRoleInGroupDTO, JSONObject.class);
        Integer errorCode = Convert.toInt(jsonObject.get("ErrorCode"));
        if (!errorCode.equals(0)) {
            throw new GlobalRunTimeException("用户数据请求错误");
        }
        List<Map> list = (List<Map>) jsonObject.get("UserIdList");
        if (CollUtil.isEmpty(list)) {
            throw new GlobalRunTimeException("数据异常");
        }
        Map map = list.get(0);
        String role = Convert.toStr(map.get("Role"));
        if (role.equals("NotMember")) {
            userIsExistGroupVO.setUserRoleInGroup(Boolean.FALSE);
        } else {
            userIsExistGroupVO.setUserRoleInGroup(Boolean.TRUE);
        }
        ImGetGroupInfoDTO imGetGroupInfoDTO = new ImGetGroupInfoDTO();
        imGetGroupInfoDTO.setGroupIdList(Arrays.asList(groupId));
        ImGroupInfoAllResultVO imGroupInfoAllResultVO = (ImGroupInfoAllResultVO) imAccountHelper.getGroupInfo(imGetGroupInfoDTO, ImGroupInfoAllResultVO.class);
        List<ImGroupInfoAllResultVO.GroupInfoDTO> collect = imGroupInfoAllResultVO.getGroupInfo().stream().filter(groupInfoDTO -> groupInfoDTO.getErrorCode().equals(0)).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            throw new GlobalRunTimeException("群不存在或已解散");
        }
        ImGroupInfoAllResultVO.GroupInfoDTO groupInfoDTO = collect.get(0);
        userIsExistGroupVO.setName(groupInfoDTO.getName());
        return userIsExistGroupVO;
    }

    @Override
    public void userAddImGroup(UserInfo oneByUserTel) {
        imAccountHelper.accountImport(Convert.toStr(oneByUserTel.getId()), oneByUserTel.getNickName(), oneByUserTel.getAvatarImg(), JSONObject.class);
    }

    @Override
    public Boolean isOfficial(String groupId) {
        return imGroupDao.isOfficial(groupId);
    }

    @Override
    public ImGroupInfoAllResultVO.GroupInfoDTO groupIsBanned(String groupId) {
        ImGetGroupInfoDTO imGetGroupInfoDTO = new ImGetGroupInfoDTO();
        imGetGroupInfoDTO.setGroupIdList(Arrays.asList(groupId));
        ImGroupInfoAllResultVO imGroupInfoAllResultVO = (ImGroupInfoAllResultVO) imAccountHelper.getGroupInfo(imGetGroupInfoDTO, ImGroupInfoAllResultVO.class);
        List<ImGroupInfoAllResultVO.GroupInfoDTO> collect = imGroupInfoAllResultVO.getGroupInfo().stream().filter(groupInfoDTO -> groupInfoDTO.getErrorCode().equals(0)).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            throw new GlobalRunTimeException("群不存在或已解散");
        }
        ImGroupInfoAllResultVO.GroupInfoDTO groupInfoDTO = collect.get(0);
        return groupInfoDTO;
    }

    /**
     * 自动新建一个群组
     * 请注意: 这里并非传统的后台新建,是由程序根据规则检测后触发.不建议正常开发调用方法使用.
     *
     * @param availableGroupDTO
     * @return
     */
    private AvailableGroupDTO getAvailableGroupDTO(AvailableGroupDTO availableGroupDTO) {
        ImGroup officialLimitFinallyData = null;
        Integer groupOfficialSum = imGroupDao.getGroupOfficialSum();
        ImGroupRule imGroupRule = new ImGroupRule();
        if (groupOfficialSum > 0) {
            // 获取规则,查看规则是否在范围内是否有指定的数据
            imGroupRule = imGroupRuleService.accordingOfficialGroupSumGetRule(groupOfficialSum + 1);
            if (BeanUtil.isEmpty(imGroupRule)) {
                throw new GlobalRunTimeException("不存在有效的群组规则");
            }
        } else {
            // 如果没有任何官方群组,直接取第一个就可以了.群一定是他的.
            List<ImGroupRule> all = imGroupRuleService.getAll();
            if (CollUtil.isEmpty(all)) {
                throw new GlobalRunTimeException("不存在有效的群组规则");
            }
            imGroupRule = all.get(0);
        }
        // 群主用户的信息
        UserInfo oneByUserTel = userInfoDao.getOneByUserTel(imGroupRule.getUserTel());
        // 组装请求条件数据
        ImCreateGroupDTO imCreateGroupDTO = new ImCreateGroupDTO();
        // 判定是否有最新的群组数据.这一步是为了保险.
        officialLimitFinallyData = imGroupDao.getOfficialLimitFinallyData();
        if (BeanUtil.isEmpty(officialLimitFinallyData)) {
            imCreateGroupDTO.setName(StrUtil.format("玛特宇宙官方{}群", 1));
        } else {
            // 请求腾讯IM 创建群组
            ImGetGroupInfoDTO imGetGroupInfoDTO = new ImGetGroupInfoDTO();
            imGetGroupInfoDTO.setGroupIdList(Arrays.asList(officialLimitFinallyData.getGroupId()));
            // 查看最新的组的名字,正则获取第几个群.
            ImGroupInfoVO groupInfo = (ImGroupInfoVO) imAccountHelper.getGroupInfo(imGetGroupInfoDTO, ImGroupInfoVO.class);
            String name = groupInfo.getGroupInfo().get(0).getName();
            List<String> all = ReUtil.findAll("[0-9]+", name, 0);
            // 匹配失败就给1.
            if (CollUtil.isEmpty(all)) {
                imCreateGroupDTO.setName(StrUtil.format("玛特宇宙官方{}群", 1));
            } else {
                // 匹配成功正常+1就可以
                imCreateGroupDTO.setName(StrUtil.format("玛特宇宙官方{}群", Convert.toInt(all.get(0)) + 1));
            }
        }
        imCreateGroupDTO.setOwnerAccount(Convert.toStr(oneByUserTel.getId()));
        imCreateGroupDTO.setFaceUrl(imGroupRule.getUrl());
        imCreateGroupDTO.setType(ImCreateGroupTypeEnum.PUBLIC);
        imCreateGroupDTO.setMaxMemberCount(2000);
        imCreateGroupDTO.setApplyJoinOption("FreeAccess");
        imCreateGroupDTO.setUserTel(oneByUserTel.getUserTel());
        imCreateGroupDTO.setSort(0);
        imCreateGroupDTO.setOfficial(1);
        imCreateGroupDTO.setStatus(0);
        adminCreateGroup(imCreateGroupDTO);
        officialLimitFinallyData = imGroupDao.getOfficialLimitFinallyData();
        availableGroupDTO.setImGroup(officialLimitFinallyData);
        availableGroupDTO.setGroupCapacity(1999);
        ImGetGroupInfoDTO imGetGroupInfoDTO = new ImGetGroupInfoDTO();
        imGetGroupInfoDTO.setGroupIdList(Arrays.asList(officialLimitFinallyData.getGroupId()));
        ImGroupInfoVO groupInfo = (ImGroupInfoVO) imAccountHelper.getGroupInfo(imGetGroupInfoDTO, ImGroupInfoVO.class);
        List<ImGroupInfoVO.GroupInfoDTO> collect = groupInfo.getGroupInfo().stream().filter(groupInfoDTO -> groupInfoDTO.getErrorCode().equals(0)).collect(Collectors.toList());
        if (!CollUtil.isEmpty(collect)) {
            availableGroupDTO.setGroupInfoDTO(collect.get(0));
        }
        return availableGroupDTO;
    }

}
